import { defineStore } from 'pinia';
import { getToken, removeToken, setToken } from '../utils/token-utils';
// 引入api请求
import { requestLogin, requestUserInfo, requestLogout } from "@/api/userlnfo"
// 引入api类型
import type { reqLoginParamType, reqUserInfoReturnType } from "@/api/userlnfo";

import {staticRoutes} from '@/router/routes'
import type {RouteRecordRaw} from 'vue-router';



/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */

// 定义小波罗类型
export interface UserInfoState{
  token :string;
  userInfo : reqUserInfoReturnType;
  menuRoutes: RouteRecordRaw[]
}
export const useUserInfoStore = defineStore('userInfo', {

	state: (): UserInfoState => ({
    token: (getToken() as string) || "",
    userInfo: {
      routes: [],
      buttons: [],
      roles: [],
      name: "",
      avatar: "",
    },
    menuRoutes: staticRoutes
  }),

	actions: {
    async login(loginParam:reqLoginParamType){
      try{
        //发送登录请求
        const result = await requestLogin(loginParam);
       //拿到结果token设置给state中
       this.token = result.token;
       //设置自动登录(持久化保存token)
       setToken(this.token)
      }catch(e){
        // 处理请求出现的问题
        return Promise.reject(e)
      }
    },
    // 用户请求方法
    async getInfo (){
      try{
        //发送用户信息请求
        const result = await requestUserInfo();
        this.userInfo = result;
      }catch (e){
        return Promise.reject(e)
      }
    },
     //退出登录的方法
     async getLogout(){
      try{
       //发送退出登录请求 
       await requestLogout();
       this.reset();
      }catch(e){
        return Promise.reject(e)
      }
     },
      //退出登录之后,请求数据的方法
      reset(){
        removeToken();
        this.token = "";
        this.userInfo = {
        routes: [],
        buttons: [],
        roles: [],
        name: "",
        avatar: "",
      };
      }
	},
});
